package io.zt.dangyuan;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.alibaba.fastjson.JSON;

import io.zt.dangyuan.object.AddressBook;
import io.zt.dangyuan.object.AddressList;


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.orhanobut.logger.Logger;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.HttpException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AddressListActivity extends BaseActivity {

    private ListView listView;
    private AddressListAdapter addressListAdapter;
    private List<AddressList.ListEntity> datas;
    private List<AddressBook.ListEntity> bookDatas;

    private List<SeaListEntity> list;
    private String groupid;
    private AddressList book;
    private String groupname;
    private ListView search_listview;
    private AddressListSearchAdapter addressListSearchAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addCenterView(R.layout.activity_address_list);
        setTitle("通讯录");
        toolbar.setNavigationIcon(R.drawable.icon_pre);
        datas = new ArrayList<AddressList.ListEntity>();
        book = new AddressList();
        list = new ArrayList<>();
        bookDatas = new ArrayList<AddressBook.ListEntity>();
        listView = (ListView) findViewById(R.id.address_list_listView);
        SearchView editText = (SearchView) findViewById(R.id.search_ed);
        search_listview = (ListView) findViewById(R.id.search_listview);


        editText.setSubmitButtonEnabled(true);
        editText.setIconifiedByDefault(true);
        editText.onActionViewExpanded();
        editText.setIconifiedByDefault(true);
        editText.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Logger.i("address","querykey="+query);
                getDate(query);
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                Logger.i("address","querychange="+newText);
                getDate(newText);

                return true;
            }
        });
        addressListAdapter = new AddressListAdapter(this, datas, bookDatas, book);

        groupid = getIntent().getStringExtra("groupid");
        groupname = getIntent().getStringExtra("groupname");

        listView.setAdapter(addressListAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (0 == position) {
                    return;
                } else if (datas.size() + 1 == position) {
                    return;
                } else if (datas.size() + 1 > position) {
                    Intent intent = new Intent(AddressListActivity.this, AddressListActivity.class);
                    AddressList.ListEntity object = datas.get(position - 1);

                    Constant.contentGroupid = object.getGroupid();
                    intent.putExtra("groupid", String.valueOf(object.getGroupid()));
                    if (groupname != null && !groupname.equals("")) {
                        intent.putExtra("groupname", groupname);
                    } else {
                        intent.putExtra("groupname", object.getGroupname());
                    }
                    startActivity(intent);

                } else if (datas.size() + 1 < position) {
                    AddressBook.ListEntity bd = bookDatas.get(position - 2 - datas.size());
                    Intent intent = new Intent(AddressListActivity.this, PeopleInfoActivity.class);
                    intent.putExtra("userid", bd.getUserid());
                    intent.putExtra("groupname", groupname);
                    startActivity(intent);
                }
            }
        });

        search_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                SeaListEntity seaListEntity = list.get(i);
                Intent intent = new Intent(AddressListActivity.this, PeopleInfoActivity.class);
                intent.putExtra("userid", seaListEntity.getUserid());
//                intent.putExtra("groupname",seaListEntity.groupname);
                startActivity(intent);
            }
        });
        webRequst();
        bookwebRequst();

    }

    Handler myH = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                String result = (String) msg.obj;
                JSONObject json = new JSONObject(result);
                JSONObject jsonObject = json.optJSONObject("data");
                Gson gson = new Gson();

                list = gson.fromJson(jsonObject.optString("list"), new TypeToken<List<SeaListEntity>>() {
                }.getType());
               Logger.i("hand",list.size()+"");

                if (list.size() > 0) {
                    Logger.i("hand","list>0");
                   /* if (addressListSearchAdapter == null) {*/
                        Logger.i("hand","adapter==null");
                        addressListSearchAdapter = new AddressListSearchAdapter(AddressListActivity.this, list);
                        search_listview.setAdapter(addressListSearchAdapter);
                     /*}else {
                        Logger.i("hand","adapter更新");
                        addressListSearchAdapter.notifyDataSetChanged();
                    }*/
                    listView.setVisibility(View.GONE);
                    search_listview.setVisibility(View.VISIBLE);

                } else {  Logger.i("hand","list<0");
                    search_listview.setVisibility(View.GONE);
                    listView.setVisibility(View.VISIBLE);

                }


            } catch (JSONException e) { Logger.i("hand","no try");
                e.printStackTrace();
            }

        }
    };

    public void getDate(String s) {
        if (s != null && !s.equals("")) {

//            try {
//                Jyhttp.getInstance(this).post(s, myH);
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        } else {
           Logger.i("222","kanbudao");
            search_listview.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
//        getMenuInflater().inflate(R.menu.menu_address_list, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void webRequst() {

        HashMap<String,Object> map = new HashMap<String,Object>();
        if (groupid != null && !groupid.equals("")) {
            map.put("groupid", groupid);
        }
        WebUtils.sendPost(AddressListActivity.this, "groupDepList", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {

                book = JSON.parseObject(data, AddressList.class);
                datas.clear();
                datas.addAll(book.getList());
                addressListAdapter.setBook(book);
                addressListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(HttpException error, String msg) {

            }
        });

    }

    public void bookwebRequst() {

        HashMap<String,Object> map = new HashMap<String,Object>();
        if (groupid != null && !groupid.equals("")) {
            map.put("groupid", groupid);
        }
        WebUtils.sendPost(AddressListActivity.this, "groupInfoList", map, new WebUtils.OnWebListenr() {
            @Override
            public void onSuccess(boolean isSuccess, String msg, String data) {
                AddressBook resultData = JSON.parseObject(data, AddressBook.class);
                bookDatas.clear();
                bookDatas.addAll(resultData.getList());
                addressListAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailed(HttpException error, String msg) {

            }
        });


    }


}
